﻿package com.cn.hjsj.base.Interceptor;

import com.cn.hjsj.base.annotation.Permission;

import com.cn.hjsj.base.validation.PermissionValidation;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

public class FreeMarkerViewInterceptor extends HandlerInterceptorAdapter
{
  public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
    throws Exception
  {
  }

  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView view)
    throws Exception
  {
    String contextPath = request.getContextPath();
    if (view != null)
      request.setAttribute("base", contextPath);
  }

  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
  {
    response.setCharacterEncoding("utf-8");
//    if ("DEBUG".equals(Parameters.getParameters("MODETYPE")))
//    {
//      return true;
//    }

    if ((handler instanceof ResourceHttpRequestHandler)) {
      return true;
    }

    HandlerMethod method = (HandlerMethod)handler;
    Permission permission = (Permission)method.getMethodAnnotation(Permission.class);

    HttpSession session = request.getSession();

    String perString = null;
    if (permission == null)
      perString = "null";
    else {
      perString = permission.value();
    }

    if ("login".equals(perString))
    {
      return true;
    }

    if ((session.getAttribute("username") == null) && (!"login".equals(perString)))
    {
      PrintWriter out = response.getWriter();
      out.println("{\"reslut\":\"nopermission\";\"message\":\"没有权限！\"}");
      out.flush();
      out.close();
      return false;
    }

    if (!PermissionValidation.cheackPermission(session.getAttribute("system_rolesId").toString(), perString)) {
      PrintWriter out = response.getWriter();
      out.println("{\"reslut\":\"nopermission\";\"message\":\"没有权限！\"}");
      out.flush();
      out.close();
      return false;
    }
    return true;
  }
}